package com.dbflow5.provider;

import com.dbflow5.config.DBFlowDatabase;
import com.dbflow5.config.DatabaseHolder;
import com.dbflow5.config.FlowManager;
import com.dbflow5.transaction.ITransaction;
import ohos.aafwk.ability.*;
import ohos.aafwk.content.Intent;
import ohos.data.rdb.ValuesBucket;
import ohos.utils.net.Uri;

import java.util.ArrayList;

public abstract class BaseContentProvider extends Ability {
    protected Class<DatabaseHolder> moduleClass;

    protected DBFlowDatabase database;

    private DataAbilityHelper mDataAbilityHelper;

    protected abstract String getDatabaseName();

    public BaseContentProvider(Class<DatabaseHolder> databaseHolderClass) {
        moduleClass = databaseHolderClass;
    }

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        database = FlowManager.getDatabase(getDatabaseName());
        mDataAbilityHelper = DataAbilityHelper.creator(this);

        if(moduleClass != null) {
            FlowManager.initModule(moduleClass);
        }else {
            FlowManager.init(this, builder -> null);
        }
    }

    @Override
    public DataAbilityResult[] executeBatch(ArrayList<DataAbilityOperation> operations) {
        return database.executeTransaction((ITransaction<DataAbilityResult[]>) databaseWrapper -> {
            DataAbilityResult[] dataAbilityResults = new DataAbilityResult[operations.size()];
            for (int index = 0; index < operations.size(); index++) {
                DataAbilityOperation operation = operations.get(index);
                if(operation.isInsertOperation()) {
                    int count = bulkInsert(operation.getUri(), operation.getValuesBucket());
                    dataAbilityResults[index] = new DataAbilityResult(operation.getUri(), count);
                    if(mDataAbilityHelper != null) {
                        mDataAbilityHelper.notifyChange(operation.getUri());
                    }
                }
            }
            return dataAbilityResults;
        });
    }

    protected abstract int bulkInsert(Uri uri, ValuesBucket contentValues);
}
